package cn.edu.ctbu.firstdata.restcontroller;

import cn.edu.ctbu.firstdata.domain.Student;
import cn.edu.ctbu.firstdata.helper.PageUtils;
import cn.edu.ctbu.firstdata.helper.R;
import cn.edu.ctbu.firstdata.service.IStudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;

@RestController
@RequestMapping(value = "/webapi/student")
@Slf4j
public class StudentRestController {
    @Autowired
    IStudentService studentService;

    @GetMapping("list")
    public PageUtils Getall(Integer pageSize, Integer pageNum){
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<Student> tempStudents = studentService.getall(pageable);
        PageUtils pageUtils = new PageUtils(tempStudents.getTotalElements(),tempStudents.getContent());
        return pageUtils;
    }

    /**
     * 示例：http://localhost:8080/webapi/student/2
     * 其中2表示id
     * @param id
     * @return
     */
    @GetMapping(value="{id}")
    public R GetById(@PathVariable Integer id){
        return R.ok("data",studentService.findById(id));
    }

    @DeleteMapping(value = "delete/{id}")
    public R DeleteById(@PathVariable Integer id){
        studentService.delete(id);
        return R.ok();
    }

    @DeleteMapping(value = "deletebyids")
    public R DeleteByIds(Integer[] ids){
        for (Integer i = 0;i < ids.length;i++)
        {
            studentService.delete(ids[i]);
        }
        return R.ok();
    }

    @PostMapping(value = "add")
    public R Add(@Valid Student student, BindingResult bindingResult)
    {
       if (bindingResult.hasErrors()){
           log.info(bindingResult.getFieldError().getDefaultMessage());
           return R.error(bindingResult.getFieldError().getDefaultMessage());
       }
        studentService.save(student);
        return R.ok("data",student);
    }
//    @PostMapping(value= "update")
//    public R Update(@Valid Student student, BindingResult bindingResult)
//    {
//        if (bindingResult.hasErrors()){
//            log.info(bindingResult.getFieldError().getDefaultMessage());
//            return R.error(bindingResult.getFieldError().getDefaultMessage());
//        }
//        studentService.save(student);
//        return R.ok("data",studentService.findById(student.getId()));
//    }
    @PostMapping(value = "updatae")
    public Integer Update(Student student){
        studentService.save(student);
        return student.getId();
    }

    @GetMapping(value = "login")
    public R login(String userName,String password) throws Exception{
        studentService.validUserNameAndPassword(userName,password);
        return R.ok();
    }
}
